﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BinPacking {
	static class Utility {
		public static T Pop<T>(this List<T> ls) {
			var item = ls.Last();
			ls.RemoveAt(ls.Count - 1);
			return item;
		}
	}

	class BinPacker {
		public List<long> Items { private get; set; }
		public List<Bin> LeastBins { get; private set; } = new List<Bin>();
		
		public long Capacity { private get; set; } = 100;

		public class Bin : List<long>
		{
			public Bin(IEnumerable<long> source) {
				foreach (var item in source) {
					Push(item);
				}
			}
			public long Sum { get; private set; } = 0;
			public long Pop(){
				var item = this.Last();
				RemoveAt(Count - 1);
				Sum -= item;
				return item;
			}
			public void Push(long item) {
				Add(item);
				Sum += item;
			}
		}

		public BinPacker(IEnumerable<long> items, long capacity) {
			Items = items.ToList();
			Items.Sort();
			Capacity = capacity;
		}

		public void TryFit()
		{
			foreach(var item in Items) {
				var binFound = false;
				foreach(var bin in LeastBins) {
					if (Capacity - bin.Sum >= item) {
						bin.Push(item);
						binFound = true;
						break;
					}
				}
				if (!binFound) LeastBins.Add(new Bin(new List<long> { item }));
			}
		}
	}
}